import 'dart:developer' as dev;

import 'package:azlistview/azlistview.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/common_language_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/model/common_language_model.dart';
import 'package:changxindianzishangwu/model/group_message_list_model.dart';
import 'package:changxindianzishangwu/pages/contacts/new_firends_page.dart';
import 'package:changxindianzishangwu/pages/contacts/search_user_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/send_some_message_page.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/provider/friend.dart';
import 'package:changxindianzishangwu/provider/friendApplication.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/widget_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimFriendshipListener.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'add_user_page.dart';
import 'contacts_titiles_page.dart';
import 'conversation_friend_page.dart';

class ContactsPage extends StatefulWidget {
  ContactsPage({Key key}) : super(key: key);

  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage>
    with AutomaticKeepAliveClientMixin {
  String packageName = "ContactsPage:";
  int count = 0;
  V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;

  @override
  void initState() {
    super.initState();
    if (!ObjectUtil.isEmptyString(getAppLoginToken()))
      // LinkManSocket.instance.connect(HttpUrls.WEB_SOCKET_URL + getUserId());

      _listingIM();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      loadUser();
      _getFriendsAddList();
    });
    //_loadUserInfo();
    getDataList();
  }

  List<CommonLanguageBean> _lists = [];

  getDataList() async {
    print('userId:${getUserInfo().userId}');
    _lists.clear();
    Map hashMap = await CommonLanguageDao.getData(1);
    if (!hashMap.containsKey("data")) {
      return;
    }
    CommonLanguageModel commonLanguageModel =
        CommonLanguageModel.fromJson(hashMap);

    if (mounted)
      setState(() {
        _lists.addAll(commonLanguageModel.data);
      });
  }

  sendMessage(value, length, userId) async {
    print("长度！！！！！！！！" + value);
    print("长度！！！！！！！！" + length.toString());
    V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin
        .v2TIMManager.v2TIMMessageManager
        .sendTextMessage(
      text: value,
      receiver: userId,
    );
    // _messages.insert(_messages.length, res.data);
    List<V2TimMessage> list = new List.empty(growable: true);
    V2TimMessage msg = res.data;
    if (res.code == 0) {
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage("c2c_" + userId, list);
      print("长度！！！！！！！！" + _lists.length.toString());
      if (_lists.length == 1) {
        if (_lists.length == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
        }
      } else {
        if (_lists.length - 1 == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
        } else if (length == 0) {}
      }
    } else {
      list.add(msg);
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage("c2c_" + userId, list);
      if (_lists.length == 1) {
        if (_lists.length == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
        }
      } else {
        if (_lists.length - 1 == length) {
          print("长度！！！！！！！！" + _lists.length.toString());
          print("长度！！！！！！！！" + length.toString());
        } else if (length == 0) {}
      }
    }
  }

  bool flaga = true;

  ap(userId) {
    if (flaga) {
      if (_lists.length > 0) {
        if (_lists.length == 1) {
          sendMessage(_lists[0].context, 1, userId);
        } else {
          for (int i = 0; i <= _lists.length; i++) {
            print(
                "=====================" + i.toString() + "==================");
            sendMessage(_lists[i].context, i, userId);
          }
        }
      } else {
        sendMessage("我们已经是好友了，快来开始聊天吧！～", 0, userId);
      }
      flaga = false;
    } else {}
  }

  void
      onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted(
          List<String> l,
          {List<V2TimFriendInfo> users}) async {
    //  getDataList();
    print("this=============" + getUserSayHello().toString());
    if (getUserSayHello() == 1 || getUserSayHello() == 3) {
      ap(users[0].userID);
    }
    users.forEach((element) {
      print("::::::::::::::element:" + element.userProfile.nickName);
    });
    print("iscomiing!!");
    print("===================tooooooooooooo");
    l.forEach((element) {
      print("===================tooooooooooooo" + element.toString());
    });

    V2TimValueCallback<List<V2TimFriendInfo>> friendRes =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .getFriendList();
    if (friendRes.code == 0) {
      List<V2TimFriendInfo> newList = friendRes.data;
      if (newList != null && newList.length > 0) {
        Provider.of<FriendListModel>(context, listen: false)
            .setFriendList(newList);

        setState(() {
          f = Provider.of<FriendListModel>(context, listen: false).friendList;
        });
      } else {
        Provider.of<FriendListModel>(context, listen: false)
            .setFriendList(List.empty(growable: true));
        setState(() {
          f = Provider.of<FriendListModel>(context, listen: false).friendList;
        });
      }
    }
  }

  void onFriendApplicationListAdded(List<V2TimFriendApplication> list) async {
    // 收到加好友申请,添加双向好友时双方都会周到这个回调，这时要过滤掉type=2的不显示
    print("收到加好友申请2");

    List<V2TimFriendApplication> newlist = List.empty(growable: true);
    list.forEach((element) {
      if (element.type != 2) {
        newlist.add(element);
      }
    });
    if (newlist.isNotEmpty) {
      Provider.of<FriendApplicationModel>(context, listen: false)
          .setFriendApplicationResult(newlist);
    }
    //TODO 也许有问题
    _getFriendsAddList();
  }

  _listingIM() {
    print("刷新了几次");
    timManager.getFriendshipManager().setFriendListener(
          listener: new V2TimFriendshipListener(
            onBlackListAdd: (infoList) {},
            onBlackListDeleted: (userList) {
              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted(
                  userList);
            },
            onFriendApplicationListAdded: (applicationList) {
              print("xxxxxxxxxxxa");
              onFriendApplicationListAdded(applicationList);
            },
            onFriendApplicationListDeleted: (userIDList) {},
            onFriendApplicationListRead: () {
              print("xxxxxxxxxxx3");
            },
            onFriendInfoChanged: (infoList) {
              print("xxxxxxxxxxx4");
              List<String> a = [];
              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted(
                  a);
            },
            onFriendListAdded: (users) async {
              print("xxxxxxxxxxx5");
              List<String> a = [];

              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted(
                  a,
                  users: users);
            },
            onFriendListDeleted: (userList) {
              onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted(
                  userList);
            },
          ),
        );
  }

  List<V2TimFriendApplication> applicationList;
  V2TimValueCallback<V2TimFriendApplicationResult> data;

  _getFriendsAddList() async {
    print("comming!!_getFriendsAddList");
    data = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .getFriendApplicationList();
    setState(() {
      count = data.data.unreadCount;
    });
  }

  initImFriendLister() {
    timManager.v2TIMFriendshipManager.setFriendListener(listener:
        V2TimFriendshipListener(onFriendApplicationListAdded: (application) {
      setState(() {
        f = Provider.of<FriendListModel>(context, listen: true).friendList;
      });
    }));
  }

  List userIDList;

  List<String> userId;

  _findUserFriends() async {}

  List<AddressBookModel> addressBookList = [];
  List<AddressBookModel> addressBookListCopy = [];

  /// 刷新事件
  Future<dynamic> _onRefreshLoadUser() {
    setState(() {
      loadUser();
    });
  }

  GroupMessageListModel someMessageModel;
  V2TimValueCallback<String> myID;

  /// 加载当前登录用户信息
  _loadUserInfo() async {
    myID = await TencentImSDKPlugin.v2TIMManager.getLoginUser();
  }

  Future<dynamic> _onRefresh() {
    setState(() {});
  }

  Future<V2TimValueCallback<List<V2TimFriendInfoResult>>> userEntity;
  List<V2TimFriendInfoResult> friendInfoResult;
  List<V2TimFriendInfo> f;
  V2TimUserFullInfo _userEntity;

  loadUser() async {
    V2TimValueCallback<List<V2TimFriendInfo>> friendRes =
        await TencentImSDKPlugin.v2TIMManager
            .getFriendshipManager()
            .getFriendList();
    f = friendRes.data;
    Provider.of<FriendListModel>(context, listen: false).setFriendList(f);
    f.forEach((element) {
      print(element.userID);
    });
    addressBookList = [];
    addressBookListCopy = [];
    userId = [];
    for (var i = 0; i < f.length; i++) {
      print(f[i].toJson());
      addressBookListCopy.add(AddressBookModel(
          name: f[i].friendRemark == null || f[i].friendRemark == ""
              ? f[i].userProfile.nickName == null ||
                      f[i].userProfile.nickName == ""
                  ? "未设置昵称"
                  : f[i].userProfile.nickName
              : f[i].friendRemark,
          headerUrl: f[i].userProfile.faceUrl ?? "",
          userId: f[i].userID,
          self: f[i].userProfile.selfSignature,
          nickNime: f[i].userProfile.nickName));
      userId.add(
        f[i].userID,
      );

      print(userId);
    }
    userEntity =
        timManager.v2TIMFriendshipManager.getFriendsInfo(userIDList: userId);
    userEntity.then((value) {
      if (value != null) {
        friendInfoResult = value.data;
        if (friendInfoResult != null && friendInfoResult.length > 0) {
          friendInfoResult.forEach((element) {
            _userEntity = element.friendInfo.userProfile;
            print("这里是数据：：：：${_userEntity.toJson()}");
          });
          addressBookList.addAll(addressBookListCopy);
          SuspensionUtil.setShowSuspensionStatus(addressBookList);
          _handleList(addressBookList);
        }
      }
    });
    setState(() {});
  }

  void _handleList(List<AddressBookModel> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin =
          PinyinHelper.getPinyinE(list[i].name == "" ? "没有姓名" : list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;

      print(list[i]);
      print(list[i].name);
      print(list[i].namePinyin);

      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(list);

    // add hotCityList.
    // addressBookList.insertAll(0, _hotCityList);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(list);

    setState(() {});
  }

  setFriendApplicationRead() async {
    V2TimCallback res = await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .setFriendApplicationRead();
    print(res.toJson());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        elevation: 0,
        title: Container(
          width: ScreenUtil().setWidth(100),
          height: ScreenUtil().setHeight(30),
          child: Text(
            "联系人 ",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(22), color: Colors.black),
          ),
        ),
        centerTitle: false,
        actions: [
          // IconButton(
          //     onPressed: () {
          //       toast("该功能暂未开放,敬请期待");
          //       Get.to(() => ContactSortingPage());
          //     },
          //     icon: Image.asset(
          //       "images/ic_sort.png",
          //       width: width(20),
          //       height: width(20),
          //     )),
          IconButton(
              onPressed: () {
                Get.to(() => NewFriendsPage());
              },
              icon: Image.asset(
                "images/ic_add_people.png",
                width: width(20),
                height: width(20),
              )),
          // InkWell(
          //   onTap: () {
          //     dev.log(packageName + "添加好友");
          //     // _findUserFriends();
          //
          //     Get.to(() => NewFriendsPage());
          //   },
          //   child: Container(
          //       width: ScreenUtil().setWidth(40),
          //       alignment: Alignment.center,
          //       margin: EdgeInsets.only(right: ScreenUtil().setWidth(10)),
          //       child: SvgPicture.asset(
          //         "images/addicon.svg",
          //         height: ScreenUtil().setHeight(28),
          //         width: ScreenUtil().setWidth(18),
          //         fit: BoxFit.contain,
          //       )),
          // ),
        ],
      ),
      body: SafeArea(
        child: Container(
          color: Colors.white,
          child: Column(
            children: [
              InkWell(
                onTap: () {
                  dev.log(packageName + "搜索聊天记录跳转");
                  Get.to(() => SearchUserPage());
                },
                child: Container(
                    height: ScreenUtil().setHeight(32),
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(left: 20),
                    margin: EdgeInsets.only(
                        left: ScreenUtil().setWidth(10),
                        top: ScreenUtil().setHeight(10),
                        right: ScreenUtil().setWidth(15)),
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(241, 241, 241, 1),
                        borderRadius: BorderRadius.circular(6)),
                    child: Text(
                      "搜索联系人、聊天记录",
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(153, 153, 153, 1)),
                    )),
              ),
              InkWell(
                onTap: () {
                  // dev.log(packageName + "新的朋友");
                  // Get.to(() => NewFriendsPage());
                },
                child: InkWell(
                  onTap: () {
                    setFriendApplicationRead();
                    _loadUserInfo();
                    Get.to(() => AddUserPage(
                          userId: myID.data,
                        )).then((value) async {
                      await loadUser();
                      await _getFriendsAddList();
                    });
                  },
                  child: Container(
                    margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
                    child: ListTile(
                      leading: Container(
                        height: ScreenUtil().setWidth(30),
                        width: ScreenUtil().setWidth(30),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6),
                          color: Color.fromRGBO(242, 181, 37, 1),
                        ),
                        child: SvgPicture.asset(
                          "images/addicon.svg",
                          height: ScreenUtil().setHeight(16),
                          width: ScreenUtil().setWidth(16),
                          fit: BoxFit.contain,
                          color: Colors.white,
                        ),
                      ),
                      title: Container(
                        margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                        child: Text(
                          "新的朋友",
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(16),
                          ),
                        ),
                      ),
                      trailing: ClipOval(
                        child: Container(
                          alignment: Alignment.center,
                          height: ScreenUtil().setHeight(16),
                          width: 16.w,
                          color: count != 0 ? Colors.red : Colors.white,
                          child: Text(
                            count.toString(),
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil().setSp(10)),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Divider(
                height: 1,
                indent: ScreenUtil().setWidth(30),
                color: Color.fromRGBO(248, 248, 248, 1),
                thickness: ScreenUtil().setHeight(1),
                endIndent: ScreenUtil().setWidth(30),
              ),
              InkWell(
                onTap: () {
                  // showToast("暂未开放");
                  Get.to(
                      SendSomeMessagePage(someMessageModel: someMessageModel));
                },
                child: Container(
                  child: ListTile(
                    leading: Container(
                      height: ScreenUtil().setWidth(30),
                      width: ScreenUtil().setWidth(30),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        color: ZdColor.rgba(33, 144, 255, 1),
                      ),
                      child: SvgPicture.asset(
                        "images/message/group.svg",
                        height: ScreenUtil().setHeight(16),
                        width: ScreenUtil().setWidth(16),
                        fit: BoxFit.contain,
                        color: Colors.white,
                      ),
                    ),
                    title: Container(
                      margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                      child: Text(
                        "群发助手",
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(16),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Divider(
                height: 1,
                indent: ScreenUtil().setWidth(30),
                color: Color.fromRGBO(248, 248, 248, 1),
                thickness: ScreenUtil().setHeight(1),
                endIndent: ScreenUtil().setWidth(30),
              ),

              // todo 隐藏
              InkWell(
                onTap: () {
                  //showToast("暂未开放");
                  // dev.log(packageName + "新的朋友");
                  Get.to(() => ContactsTitilesPage());
                },
                child: Container(
                  child: ListTile(
                    leading: Container(
                      height: ScreenUtil().setWidth(30),
                      width: ScreenUtil().setWidth(30),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        color: Color.fromRGBO(0, 220, 169, 1),
                      ),
                      child: SvgPicture.asset(
                        "images/title.svg",
                        height: ScreenUtil().setHeight(16),
                        width: ScreenUtil().setWidth(16),
                        fit: BoxFit.contain,
                        color: Colors.white,
                      ),
                    ),
                    title: Container(
                      margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
                      child: Text(
                        "标签",
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(16),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: AzListView(
                  data: addressBookList,
                  itemCount: addressBookList.length,
                  itemBuilder: (BuildContext context, int index) {
                    AddressBookModel model = addressBookList[index];
                    print(model.name);
                    _userEntity =
                        friendInfoResult[index].friendInfo.userProfile ?? "";

                    return getListItem(context, model, _userEntity);
                  },
                  padding: EdgeInsets.zero,
                  susItemBuilder: (BuildContext context, int index) {
                    AddressBookModel model = addressBookList[index];
                    String tag = model.getSuspensionTag();
                    return WidGetUtils.getSusItem(context, tag);
                  },
                  indexBarOptions: IndexBarOptions(
                      textStyle:
                          TextStyle(fontSize: 12.sp, color: Color(0xFF666666))),
                  indexBarAlignment: Alignment.centerRight,
                  indexBarData: [...kIndexBarData],
                  indexBarWidth: 20.w,
                  indexBarHeight: 500.w,
                  indexBarItemHeight:
                      MediaQuery.of(context).size.height > 740.w ? 16 : 11,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  List<AddressBookModel> someUser = [];

  Widget getListItem(BuildContext context, AddressBookModel model,
      V2TimUserFullInfo userEntity,
      {double susHeight = 60}) {
    //print("::tihis::${userEntity.faceUrl}");
    return Container(
      alignment: Alignment.bottomCenter,
      padding: EdgeInsets.only(left: width(15), right: width(20)),
      height: 60,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            onTap: () {
              Get.to(() => ConversationFriendPage(
                    model: model,
                    type: 2,
                  )).then((value) async {
                await loadUser();
              });
            },
            child: Row(
              children: [
                Container(
                    height: width(40),
                    width: width(40),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(6),
                      child: CachedNetworkImage(
                        imageUrl: model.headerUrl,
                        fit: BoxFit.cover,
                      ),
                    )),
                Expanded(
                  flex: 1,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 8, right: 15),
                    child: Text(
                      model.name ?? "",
                      style: TextStyle(fontSize: sp(15)),
                    ),
                  ),
                ),

                ///在线时间
                // _onlineView()
              ],
            ),
          ),
          Divider(
            height: 1,
            indent: width(48),
          )
        ],
      ),
    );
//    return Column(
//      mainAxisSize: MainAxisSize.min,
//      children: <Widget>[
//        Offstage(
//          offstage: !(model.isShowSuspension == true),
//          child: getSusItem(context, model.getSuspensionTag(),
//              susHeight: susHeight),
//        ),
//        ListTile(
//          title: Text(model.name),
//          onTap: () {
//            LogUtil.e("onItemClick : $model");
//            Utils.showSnackBar(context, 'onItemClick : ${model.name}');
//          },
//        )
//      ],
//    );
  }

  static Column _onlineView() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Image.asset(
          "images/ic_gray_cir.png",
          width: width(8),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 3),
          child: Text(
            "时长",
            style: TextStyle(fontSize: sp(10), color: AppColor.colorText85),
          ),
        )
      ],
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => false;
}
